# frozen_string_literal: true
class V1::DoorsController < V1::ApplicationController

  before_action :authenticate_editor_by_token

  def show
    @village = @current_editor.village
    @floors = @village.editors.with_role(:floor)
    @estates = @village.editors.with_role(:estate)
    @users = @village.users.where('telephone = :value OR floor_code = :value',{value: params[:keyword]})
    render  :show
  end

  def search
     @village = @current_editor.village
     @users = @village.users.keyword(params[:keyword]).distinct
     render  :search
  end

  def entrance
    user = User.where(telephone: params[:user_telephone]).first

    raise CommonError::CustomMessageError.new('没有这个业主') if user.blank?

    uploaded_io = params[:photo]
    photo_name = uploaded_io.original_filename if uploaded_io
    idcard = Idcard.where(
      name: params[:name],
      gender: params[:gender],
      nation: params[:nation],
      photo: photo_name,
      birthday: params[:birthday],
      code: params[:card_code],
      card_valid: params[:card_valid],
      started_at: params[:started_at],
      expired_at: params[:expired_at]
    ).first
      logger.info "idcard: #{idcard.id if idcard}"
    if idcard.nil?
        logger.info "创建记录"
      idcard = Idcard.create(
        name: params[:name],
        gender: params[:gender],
        nation: params[:nation],
        photo: params[:photo],
        birthday: params[:birthday],
        code: params[:card_code],
        card_valid: params[:card_valid],
        started_at: params[:started_at],
        expired_at: params[:expired_at]
      )
    end

    guest = Guest.find_or_create_by(
      idcard: idcard,
      name: params[:name]
    )

    content = "#{params[:name]} 想进来"
    extras = {
      content: content,
      guest_id: guest.id.to_s,
      editor_id: @current_editor.id.to_s
    }

    JpushService.new(user.registration_id, extras, content).invoke

    # render json: {editor_id: @current_editor.id.to_s, guest_id: guest.id.to_s}.to_json
  end
end
